package com.web_bloks.storage.client;

import com.google.gwt.gears.client.Factory;
import com.google.gwt.gears.client.localserver.LocalServer;
import com.google.gwt.gears.client.localserver.ManagedResourceStore;
import com.google.gwt.gears.client.localserver.ManagedResourceStoreCompleteHandler;
import com.google.gwt.gears.client.localserver.ManagedResourceStoreErrorHandler;
import com.google.gwt.gears.client.localserver.ManagedResourceStoreProgressHandler;
import com.web_bloks.system.client.Logger;

/**
 * 
 * @author Jean-Lou Dupont
 *
 */
public class GearsOffline {

	final GearsEventHandler gh = new GearsEventHandler();
	ManagedResourceStore ms = null;
	LocalServer ls = null;
	
	String storeName = null;
	String manifestUrl = null;
	
	boolean available = false;
	boolean enabled   = false;
	
	protected GearsOffline() {	
	}
	
	public boolean isAvailable() {
		return available;
	}
	
	public boolean isEnabled() {
		return enabled;
	}
	
	public void setup(String storeName, String manifestUrl) {
		
		this.storeName = new String(storeName);
		this.manifestUrl = new String(manifestUrl);
		
		Factory f = Factory.getInstance();
		
		if (null==f) {
			Logger.logInfo(this.getClass()+".setup:  GEARS NOT available");			
			return;
		}
		available = true;
		
		Logger.logInfo(this.getClass()+".setup:  GEARS AVAILABLE");

		try {
			ls = f.createLocalServer();
		} catch(Exception e) {
			ls = null;
		}
		if ( null == ls ) {
			Logger.logInfo(this.getClass()+".setup:  GEARS AVAILABLE *but* user denied access... probably");
			return;
		}
		
		enabled = true;
		
		ms = ls.createManagedStore( this.storeName );
		ms.setEnabled(true);
		ms.setManifestUrl( this.manifestUrl );
	
		ms.setOnCompleteHandler( gh );
		ms.setOnErrorHandler( gh );
		//ms.setOnProgressHandler( gh );
	
		ms.checkForUpdate();
			
		Logger.logInfo(this.getClass()+".setupGears: init completed, currentVersion["+ms.getCurrentVersion()+"]");

	}
	
	final class GearsEventHandler 
		implements ManagedResourceStoreCompleteHandler, ManagedResourceStoreErrorHandler, ManagedResourceStoreProgressHandler {

		public void onComplete(ManagedResourceStoreCompleteEvent event) {
			String version = event.getNewVersion();
			if (null!=version && version.length()!=0)
				Logger.logInfo(this.getClass()+".onComplete, NEW version=" + version);	
		}
	
		public void onError(ManagedResourceStoreErrorEvent error) {
			Logger.logInfo(this.getClass()+".onError, msg=" + error.getMessage());
		}
	
		public void onProgress(ManagedResourceStoreProgressEvent event) {
			Logger.logInfo(this.getClass()+".onProgress, files completed="+event.getFilesComplete());
		}
	
	}
	

}//
